package scribes.mybus.ejb;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.persistence.EntityManager;

import scribes.mybus.data.bus;


public class FileParser {
	private EntityManager data;

	public EntityManager getData() {
		return data;
	}
	public void setData(EntityManager data) {
		this.data = data;
	}
	public void parseBusDataDetails(String fileName) {
		try {
		
			File file= new File(fileName);
			FileInputStream fstream = new FileInputStream("C:\\Users\\Manasa\\ws\\23.txt");
			
			DataInputStream in = new DataInputStream(fstream);
		
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			
			int counter = 0;
			
			while ((strLine = br.readLine()) != null) {

				
				counter++;
				System.out.println(strLine);
				
				bus busData = parseBusDataLine(strLine);
				
				if (busData != null) {
				
					data.persist(busData);
				}
			}
			
			System.out.println("Total number of records processed: " + counter);

			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public bus parseBusDataLine(String strLine){

		String valueDelim = ","; 
		try {
			String values[] = strLine.split(valueDelim);
			for(int i=0;i<values.length;i++){
				System.out.println("value "+values[i]);
			}
			bus busData = setBusDetails(values);
			return busData;
		} catch (Exception ex) {
			return null;
		}
	}
	public bus setBusDetails(String[] values)
	{
		bus busData = new bus();
		busData.setId(Integer.parseInt(values[0]));
		busData.setBus_id(Integer.parseInt(values[1].trim()));
		busData.setDriver_id(Integer.parseInt(values[2].trim()));
		busData.setLatitude(Double.parseDouble(values[3].trim()));
		busData.setLocation(values[4].trim());
		busData.setLongitude(Double.parseDouble(values[5].trim()));
		busData.setMessage(values[6].trim());
		busData.setName(values[7].trim());
		busData.setOperation_code(values[8].trim());
		busData.setPassenger_count(Integer.parseInt(values[9].trim()));
		busData.setRoute_status(values[10].trim());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			busData.setTimestamp(formatter.parse(values[11].trim()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return busData;
	}
}
